//
//  UserAccont.swift
//  Weibo10
//
//  Created by zhangbaiqiang on 16/1/8.
//  Copyright © 2016年 itheima. All rights reserved.
//  使用网络返回的字典数据, 转成模型数据  (定义过期日期属性,便于后续判断token的有效期)

import UIKit

/// 用户账户模型
/// - see:[http://open.weibo.com/wiki/OAuth2/access_token](http://open.weibo.com/wiki/OAuth2/access_token)
class UserAccount: NSObject,NSCoding{
    
    //用于调用access_token 接口获取授权后的access token
    var access_token: String?
    // access_token 的生命周期,单位是秒
    var expires_in: NSTimeInterval = 0  {//模型总整形数据要先赋值0
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    // 当前授权用户UID
    var uid: String?
    
    //access_token过期日期
    var expiresDate: NSDate?
    
   
    
    //友好显示名称
    var name:String?
    //用户头像地址: (大图) 180×180像素
    var avatar_large: String?
    
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    override var description: String {
        let keys = ["access_token", "expires_in", "expiresDate", "uid", "name", "avatar_large"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    
    /**
     实现保存对象--归档
     */
    func saveUserAccount() {
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        path = (path as NSString).stringByAppendingPathComponent("account.plist")
        print(path)
        
        //归档使用NSKeyedArchiver
        //解档使用NSkeyedUnarchiver
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    // MARK: - 归档&解档
    /**
    归档-将对象以二进制形式保存至磁盘前被调用
    
    - parameter aCoder: 归档属性-告诉对象属性如何归档
    */
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    /**
    *  解档
    */
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    
    }
}


